package xnj.lazydog.btcontroller.ButtonEdit;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import xnj.lazydog.btcontroller.HexStringUtils.HexStr;
import xnj.lazydog.btcontroller.MainActivity;
import xnj.lazydog.btcontroller.MyViews.SwitchButton;
import xnj.lazydog.btcontroller.R;

public class SendButtonManager {

    List<SendButton>  sbs = new ArrayList<>();
    public boolean isEditingButton=false;
    Button [] bts;

    Context context;

    SendButton sendButton;

    SharedPreferences sp;
    @SuppressLint("ClickableViewAccessibility")
    public SendButtonManager(Context context, final Button []send_buttons, SharedPreferences sp, SendButtonEventListener l)
    {
        String name;
        this.sp = sp;
        //SharedPreferences.Editor editor = sp.edit();
        this.context = context;
        bts = send_buttons;
        listener = l;
        if(sbs.size()>0)
            sbs.clear();
        for(int i=0;i<send_buttons.length;i++)
        {

            sendButton = new SendButton();
            sendButton.button = send_buttons[i];

            name = sp.getString("button_name"+i,"no---name");
            if(!"no---name".equals(name))
            {
                sendButton.button.setText(name);
            }

            sendButton.isHex = sp.getBoolean("button_hex"+i,false);
            Log.w("SENDBUTTON", "SendButtonManager: "+sendButton.isHex );
            sendButton.up_text = sp.getString("button_up" + i, "");
            sendButton.down_text = sp.getString("button_down" + i, "" + (char)('A' + i));

            sbs.add(sendButton);
            send_buttons[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });

            send_buttons[i].setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {


                    if(event.getAction()==MotionEvent.ACTION_DOWN) {
                        // 发送模式
                        if (!isEditingButton)
                        {
                            int i = getButtonIndex(v);
                        if (i >= 0)
                        {
                            byte[] b;
                            if(sbs.get(i).isHex)
                                b = HexStr.hexStr2Bytes(sbs.get(i).down_text);
                            else
                                b= HexStr.str2Bytes(HexStr.replaceTurnLine(sbs.get(i).down_text));

                            listener.onButtonSend(b,sbs.get(i).down_text);
                        }
                        }
                    }
                    if(event.getAction()==MotionEvent.ACTION_UP)
                    {
                        if(isEditingButton)  // 编辑模式
                        {
                            int i = getButtonIndex(v);
                            if(i>=0) {
                                showButtonEditDialog(sbs.get(i));
                                listener.onDialogShow(sbs.get(i));
                            }
                        }else                // 发送模式
                        {
                            int i = getButtonIndex(v);
                            if (i >= 0)
                            {
                                byte[] b;

                                if(sbs.get(i).isHex)
                                    b = HexStr.hexStr2Bytes(sbs.get(i).up_text);
                                else
                                    b= HexStr.str2Bytes(HexStr.replaceTurnLine(sbs.get(i).up_text));

                                listener.onButtonSend(b,sbs.get(i).up_text);
                            }
                        }
                    }
                    return false;

                }
            });
        }
    }


    private EditText nameEdit;
    EditText upText;
    EditText downText;

    Button confirm;
    Button finish;

    SwitchButton hex_button;

    TextView hex_press,hex_release;


    void formatText(EditText editText)
    {
        String s = editText.getText().toString();
        s = HexStr.formatHexString(s);
        s = s.toUpperCase();
        editText.setText(s);
        editText.setSelection(s.length());
    }


    void updateRawData(boolean isHex,EditText editText,TextView textView)
    {
        String s = editText.getText().toString();


            if (!isHex) {
                textView.setText(HexStr.bytes2HexStr(HexStr.str2Bytes(HexStr.replaceTurnLine(s))));
            } else {

                textView.setText(HexStr.bytes2HexStr(HexStr.hexStr2Bytes(s)));
            }

    }


    void showButtonEditDialog(final SendButton sb)
    {
        //isEditingButton = true;


        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate( R.layout.button_edit_layout,null);
        final AlertDialog dialog = builder.setView(view).create();

        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        hex_button = view.findViewById(R.id.button_hex_button);
        nameEdit =view.findViewById(R.id.button_name);
        upText=view.findViewById(R.id.up_text);
        downText = view.findViewById(R.id.down_text);
        confirm = view.findViewById(R.id.confirm_button);
        finish = view.findViewById(R.id.finish_button);
        hex_press = view.findViewById(R.id.raw_button_press_data);
        hex_release = view.findViewById(R.id.raw_button_release_data);

        nameEdit.setText(sb.button.getText());
        upText.setText(sb.up_text);
        downText.setText(sb.down_text);
        hex_button.setCheckImm(sb.isHex);

        updateRawData(sb.isHex,downText,hex_press);
        updateRawData(sb.isHex,upText,hex_release);


        hex_button.setOnCheckedChangedListener(new SwitchButton.OnCheckedChangedListener() {
            @Override
            public void onCheckedChanged(boolean isChecked) {

                sb.isHex =isChecked;
                if(isChecked)
                {
                    formatText(upText);
                    formatText(downText);
                }
                updateRawData(isChecked,downText,hex_press);
                updateRawData(isChecked,upText,hex_release);

            }
        });

        downText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(sb.isHex) {
                    if (!HexStr.isHexFormatOK(s.toString())||HexStr.hasLowerCase(s))
                    {
                        formatText(downText);

                    }
                }
                updateRawData(sb.isHex,downText,hex_press);
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        upText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if(sb.isHex) {

                    if (!HexStr.isHexFormatOK(s.toString())||HexStr.hasLowerCase(s))
                    {
                        formatText(upText);
                    }
                }
                updateRawData(sb.isHex,upText,hex_release);
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                sb.up_text = upText.getText().toString();
//                sb.down_text = downText.getText().toString();
//                sb.button.setText(nameEdit.getText());
//                saveButtonOption(getButtonIndex(sb.button));
//
//                isEditingButton = false;
                dialog.dismiss();
            }
        });

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sb.up_text = upText.getText().toString();
                sb.down_text = downText.getText().toString();
                sb.button.setText(nameEdit.getText());

                saveButtonOption(getButtonIndex(sb.button));
                dialog.dismiss();
            }
        });



        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                //Log.w("DIALOG","dismissed");
                listener.onDialogDismissed(sb);
                //isEditingButton = false;
            }
        });

        dialog.show();
    }


    private void saveButtonOption(int index)
    {
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("button_up"+index,sbs.get(index).up_text)
                .putString("button_down"+index,sbs.get(index).down_text)
                .putString("button_name"+index,sbs.get(index).button.getText().toString())
                .putBoolean("button_hex"+index,sbs.get(index).isHex)
                .apply();
    }

    private void copyToClipBoard(String content)
    {
        ClipboardManager manager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if(manager!=null)
            manager.setPrimaryClip(ClipData.newPlainText("text",content));
    }


    private int getButtonIndex(View v)
    {
        int id = -1;
        for(int i=0;i<bts.length;i++)
        {
            if(bts[i]==v)
                return i;
        }
        return id;
    }


    SendButtonEventListener listener;

    public interface  SendButtonEventListener {
        void onButtonSend(byte[] b,String s);
        void onDialogShow(SendButton sb);
        void onDialogDismissed(SendButton sb);
    }
}
